package com.doge.calcalbum.business.album.picture

import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.setPadding
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import com.doge.calcalbum.R
import com.doge.calcalbum.business.ITEM_MORE
import com.doge.calcalbum.business.account.AccountHelper
import com.doge.calcalbum.business.entry.EntryAsCoverActivity
import com.doge.calcalbum.business.album.AlbumEditNameDialogFragment
import com.doge.calcalbum.business.album.AlbumRepository
import com.doge.calcalbum.business.album.AlbumViewModel
import com.doge.calcalbum.business.entry.EntryActivity
import com.doge.calcalbum.core.BaseFragment
import com.doge.calcalbum.core.base.adapters.ITEM_CLICKED
import com.doge.calcalbum.core.base.adapters.ITEM_LONG_CLICKED
import com.doge.calcalbum.databinding.FragmentAlbumPictureBinding
import com.doge.calcalbum.db.model.Album
import com.doge.calcalbum.utils.dp
import com.doge.calcalbum.utils.setOnClickCallback
import com.doge.calcalbum.utils.systemWindowInsetsTop
import com.doge.calcalbum.widgets.GridItemDecoration
import com.doge.calcalbum.widgets.SheetDialog

class AlbumPictureFragment : BaseFragment() {
    private var innerBinding: FragmentAlbumPictureBinding? = null
    private val binding get() = innerBinding!!
    private val viewModel by viewModels<AlbumViewModel>()
    private val adapter by lazy { AlbumPictureAdapter() }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        innerBinding =
            innerBinding ?: FragmentAlbumPictureBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        systemWindowInsetsTop.observe(viewLifecycleOwner) {
            binding.fitsSys.setPadding(it / 2)
        }
        binding.createAlbum.setOnClickCallback {
            AlbumEditNameDialogFragment.newInstance(Album.TYPE_PICTURE).show(childFragmentManager)
        }
        binding.recyclerView.itemAnimator = null
        val itemDecoration = object : GridItemDecoration(3.dp, Color.TRANSPARENT) {
            override fun getItemSidesIsHaveOffsets(itemPosition: Int) =
                arrayOf(itemPosition % 2 != 0, false, itemPosition % 2 != 1, false)
        }
        binding.recyclerView.addItemDecoration(itemDecoration)
        binding.recyclerView.layoutManager = GridLayoutManager(binding.recyclerView.context, 2)
        binding.recyclerView.adapter = adapter
        adapter.setListener(::handleAdapterCallback)
        viewModel.pictureAlbumList.observe(viewLifecycleOwner) {
            adapter.submitList(it)
        }
    }

    private fun handleAdapterCallback(action: String, item: Any?) {
        when (action) {
            ITEM_CLICKED -> EntryActivity.start(
                context, (item as? Album?)?.id,
                (item as? Album?)?.type
            )
            ITEM_LONG_CLICKED -> showOperationDialog((item as? Album?))
            ITEM_MORE -> showOperationDialog((item as? Album?))
        }
    }

    private fun showOperationDialog(album: Album?) {
        val activity = activity ?: return
        if (album == null) return
        SheetDialog.Builder(activity)
            .addMenu(getString(R.string.rename)) { _, _ ->
                AlbumEditNameDialogFragment.newInstance(
                    album.type, album.id, album.title
                ).show(childFragmentManager)
            }
            .addMenu(getString(R.string.set_cover)) { _, _ ->
                EntryAsCoverActivity.start(activity, album.id)
            }
            .apply {
                if (album.id != Album.DEFAULT_PICTURE_ID &&
                    album.id != Album.DEFAULT_VIDEO_ID
                ) {
                    addMenu(getString(R.string.delete)) { _, _ ->
                        AlbumRepository.get().delete(album)
                    }
                }
            }
            .create().show()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding.createAlbum.setOnClickListener(null)
        binding.recyclerView.adapter = null
        adapter.setListener(null)
        innerBinding = null
    }

    companion object {
        fun newInstance(): AlbumPictureFragment {
            return AlbumPictureFragment()
        }
    }
}